package com.aviccxzx.smarthome.ConfigModule;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.utils.DialogUtil;
import com.aviccxzx.smarthome.utils.NetUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("InflateParams")
public class GosAirlinkChooseDeviceWorkWiFiActivity extends
        GosConfigModuleBaseActivity implements OnClickListener {

    private AlertDialog create;
    private ArrayList<ScanResult> wifiList;

    /**
     * wifi信息
     */
    public WifiInfo wifiInfo;

    /**
     * The et SSID
     */
    private EditText etSSID;

    /**
     * The et Psw
     */
    private EditText etPsw;

    /**
     * The btn Next
     */
    private Button btnNext;

    /**
     * The ll ChooseMode
     */
    private LinearLayout llChooseMode;

    /**
     * The cb Laws
     */
    private CheckBox cbLaws;

    /**
     * The tv Mode
     */
    private TextView tvMode;

    /**
     * The img WiFiList
     */
    private ImageView imgWiFiList;

    /**
     * 配置用参数
     */
    private String workSSID, workSSIDPsw;

    /**
     * The data
     */
    List<String> modeList;

    /**
     * The Adapter
     */
    GosModeListActivity.ModeListAdapter modeListAdapter;

    /**
     * The modeNum
     */
    public static int modeNum = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gos_airlink_choose_device_workwifi);

        initView();
        initData();
        ininEvent();
        showInfo();
    }

    public void showInfo() {
        new DialogUtil(this, true, true, "添加网关仅支持2.4G网络，请确认连接的是2.4G网络（可通过查询家用路由器的网络无线速率进行确认）", "取消", "确定", new DialogUtil.SureInterfance() {
            @Override
            public void sureTodo() {
            }

            @Override
            public void cancle() {

            }
        }).showCustomDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();

//        workSSIDPsw = spf.getString("workSSIDPsw", "");
//        if (!TextUtils.isEmpty(workSSIDPsw))
//            etPsw.setText(workSSIDPsw);

    }

    private void initView() {
        ((TextView) findViewById(R.id.title_tv)).setText("添加智能网关");
        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        //		tvMode = (TextView) findViewById(R.id.tvMode);
        etSSID = (EditText) findViewById(R.id.etSSID);
        etPsw = (EditText) findViewById(R.id.etPsw);
        cbLaws = (CheckBox) findViewById(R.id.cbLaws);
        btnNext = (Button) findViewById(R.id.btnNext);
        llChooseMode = (LinearLayout) findViewById(R.id.llChooseMode);
        llChooseMode.setVisibility(View.GONE);
    }

    private void ininEvent() {
        btnNext.setOnClickListener(this);
        //		imgWiFiList.setOnClickListener(this);
        llChooseMode.setOnClickListener(this);
        cbLaws.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                String psw = etPsw.getText().toString();

                if (isChecked) {
                    etPsw.setInputType(0x90);
                } else {
                    etPsw.setInputType(0x81);
                }
                etPsw.setSelection(psw.length());
            }
        });
    }

    private void initData() {
        // workSSID = spf.getString("workSSID", "");

        modeList = new ArrayList<String>();
        String[] modes = this.getResources().getStringArray(R.array.mode);
        for (String string : modes) {
            modeList.add(string);
        }

        workSSID = NetUtils.getCurentWifiSSID(this);
        if (!TextUtils.isEmpty(workSSID)) {
            etSSID.setText(workSSID);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_title_left_view:
                finish();
                break;
            case R.id.btnNext:
                workSSID = etSSID.getText().toString();
                workSSIDPsw = etPsw.getText().toString();

                spf.edit().putString("workSSID", workSSID).commit();
                spf.edit().putString("workSSIDPsw", workSSIDPsw).commit();


                if (!TextUtils.isEmpty(workSSID) /*&& !TextUtils.isEmpty(workSSIDPsw)*/) {
                    toAirlinkReady();
                } else {
                    App.getApp().showToast("请输入WIFI名称");
                }

                break;


            case R.id.llChooseMode:
                Intent intent = new Intent(this, GosModeListActivity.class);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    /**
     * 添加网关的第二步：。。。。。。。。。。。。。。。。。。。。
     */
    private void toAirlinkReady() {
        // 需要记录所有配置过的wifi和密码

        try {
            String mypass = spf.getString("mypass", "");
            if (TextUtils.isEmpty(mypass)) {
                JSONObject mUserAndPass = new JSONObject();

                mUserAndPass.put(workSSID, workSSIDPsw);
                spf.edit().putString("mypass", mUserAndPass.toString())
                        .commit();
            } else {
                JSONObject obj = new JSONObject(mypass);

                obj.put(workSSID, workSSIDPsw);

                spf.edit().putString("mypass", obj.toString()).commit();

            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        spf.edit().putString("workSSID", workSSID).commit();
        spf.edit().putString("workSSIDPsw", workSSIDPsw).commit();

        Intent intent = new Intent(this, GosAirlinkReadyActivity.class);
        startActivity(intent);
        finish();
    }

	/*
     * // 检查当前使用的WiFi是否曾经用过 protected boolean checkworkSSIDUsed(String workSSID)
	 * { if (spf.contains("workSSID")) { if (spf.getString("workSSID",
	 * "").equals(workSSID)) { return true; } } return false; }
	 */


    // 屏蔽掉返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //            quitAlert(this);
            finish();
            return true;
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                quitAlert(this);
                break;
        }

        return true;
    }

    class WifiListAdapter extends BaseAdapter {

        ArrayList<ScanResult> xpgList;

        public WifiListAdapter(ArrayList<ScanResult> list) {
            this.xpgList = list;
        }

        @Override
        public int getCount() {
            return xpgList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            Holder holder;
            if (view == null) {
                view = LayoutInflater.from(
                        GosAirlinkChooseDeviceWorkWiFiActivity.this).inflate(
                        R.layout.item_gos_wifi_list, null);
                holder = new Holder(view);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }

            String ssid = xpgList.get(position).SSID;
            holder.getTextView().setText(ssid);

            return view;
        }

    }

    class Holder {
        View view;

        public Holder(View view) {
            this.view = view;
        }

        TextView textView;

        public TextView getTextView() {
            if (textView == null) {
                textView = (TextView) view.findViewById(R.id.SSID_text);
            }
            return textView;
        }

    }
}
